import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import Slider from 'material-ui/Slider';
import FontIcon from 'material-ui/FontIcon';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';

import AvatarEditor from 'react-avatar-editor';

export default class Corp extends Component {
  initState = {
    title: '修改图片',
    targetName: null,
    width: 560,
    height: 350,
    scale: 1.2,
    rotate: null,
    borderRadius: null,
    initImage: null,
    // 照片比例
    showScale: 1.6,
    hasChangeImg: false,
  };

  constructor(props) {
    super(props);
    this.state = this.initState;
  }
  
  componentWillReceiveProps(nextProps) {
    if (nextProps.method) {
      let width;
      let height;
      switch(nextProps.method)
      {
        case 'cover': 
          width = 560;
          height = 224;
          if (nextProps.isSmallViewport) {
            if (window.innerWidth < 610) {
              width = window.innerWidth - 50;
              height = width / 2.5;
            }
          }
          this.setState({
            title: '修改活动封面', 
            width: width, 
            height: height, 
            showScale: 2.5,
            targetName: nextProps.method
          });
        break;
        case 'userImg':
          width = 350;
          height = 350;
          if (nextProps.isSmallViewport) {
            if (window.innerWidth < 400) {
              width = window.innerWidth - 50;
              height = window.innerWidth - 50;
            }
          }
          this.setState({
            title: '修改头像', 
            width: width, 
            height: height, 
            showScale: 1,
            targetName: nextProps.method
          });
        break;
        // case 'wrap': 
        //   this.setState({
        //     title: '修改背景图片', 
        //     width: 560, 
        //     height: 350, 
        //     targetName: nextProps.method
        //   });
        // break;
        default: 
        break;
      }
    }
  }

  /**
   * 限制相片尺寸
   */
  checkSize = (size) => {
    var isAllow = false;
    var maxSize = 2000 * 1024;
    isAllow = size <= maxSize;
    return isAllow;
  };

  /**
   * 限制相片类型
   */
  checkType = (type) => {
    if (type == 'image/jpeg') {
      return true;
    } else {
      return false;
    }
  };

  /**
   * 上传前对照片进行预处理
   */
  // window.webkitURL.createObjectURL(file);
  initUploadImage = (e) => {
    let file = e.target.files[0];

    if (this.checkSize(file.size)) {
      if (this.checkType(file.type)) {
        let src = window.URL.createObjectURL(file);
        this.setState({
          initImage: src,
          hasChangeImg: true
        });
      } else {
        this.props.handleOpenSnackbar('暂时只上传支持jpeg/jpg格式图片，囧...');
      }
    } else {
      this.props.handleOpenSnackbar('图片大小未通过，请选择小于2M的图片');
    }
  };

  /**
   * 储存相片的base64
   */
  // getImage() getCroppingRect()
  handleSave = () => {
    let canvas;
    let canvasScaledUrl;

    if (this.props.method == 'wrap') {
      canvas = this.editor.getImage();
      canvasScaledUrl = this.editor.getImageScaledToCanvas().toDataURL();
    } else if (this.props.method == 'cover') {
      canvas = this.editor.getImage();
      canvasScaledUrl = this.editor.getImageScaledToCanvas().toDataURL();
    } else {
      canvas = this.editor.getImageScaledToCanvas();
      canvasScaledUrl = this.editor.getImageScaledToCanvas().toDataURL();
    }

    this.props.handleChange(this, this.state.targetName, canvasScaledUrl, canvas);
    this.handleClose();
  };

  /**
   * 设置ref
   */
  setEditorRef = (editor) => {
    if (editor) this.editor = editor
  };

  /**
   * 关闭本会话框
   */
  handleClose = () => {
    this.setState(this.initState);
    this.props.handleClose();
  };

  render() {
    const actions = [
      <Slider
        style={styles.slider}
        value={this.state.scale}
        max={2}
        min={1}
        onChange={(e, v) => this.setState({scale: v})} 
      />,
      <FlatButton
        label="取消"
        primary={true}
        onTouchTap={this.handleClose}
      />,
      <FlatButton
        label="剪裁"
        primary={true}
        onTouchTap={this.handleSave}
      />,
    ];

  	return (
	  	<Dialog
        modal={false}
        actions={actions}
        title={this.state.title}
        autoScrollBodyContent={true}
        open={this.props.open}
        onRequestClose={this.handleClose}
        bodyStyle={{padding: 0}}
        overlayStyle={{backgroundColor: 'rgba(0,0,0,0.12)'}}
        contentStyle={{
          width: this.props.isSmallViewport ? '100%' : this.state.width + 50,  
        }}
      >
        <div style={{height: this.state.height + 54}}>
          {this.state.hasChangeImg ? 
            <AvatarEditor 
              ref={this.setEditorRef}
              image={this.state.initImage}
              scale={this.state.scale}
              rotate={0}
              width={this.state.width}
              height={this.state.height}
              onSave={this.handleSave}
              style={{
                marginLeft: 'auto',
                marginRight: 'auto'
              }}
            />
            : <IconButton 
              iconStyle={{color: 'rgb(255,255,255)'}} 
              style={styles.upload}
            >
              <FontIcon className="icon-file_upload" />
              <input 
                type="file" 
                className="upload-file"
                onChange={this.initUploadImage}
                accept="image/png, image/gif, image/jpg, image/jpeg" />
            </IconButton>
          }
        </div>
      </Dialog>
  	);
  }
};

const styles = {
  upload: {
    position: 'relative',
    backgroundColor: 'rgba(0,0,0,0.24)',
    width: 128,
    height: 128
  },
  slider: {
    marginLeft: 24,
    marginRight: 24
  }
}